<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">

        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="物料名称" v-if="permissionStore.hasPermisson('wllb.cx')">
              <a-input v-if="id == 1" allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData"
                       @press-enter="huiche"/>
              <a-input v-if="id == 2" allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData2"
                       @press-enter="huiche2"/>
            </a-form-item>
            <a-form-item label="物料编号" v-if="permissionStore.hasPermisson('wllb.cx')">
              <a-input v-if="id == 1" allow-clear class="bacClass" placeholder="" v-model="pageData.materialCode"
                       @press-enter="huiche"/>
              <a-input v-if="id == 2" allow-clear class="bacClass" placeholder="" v-model="pageData.materialCode1"
                       @press-enter="huiche2"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar v-if="id == 1" :items="[
            `${permissionStore.hasPermisson('wllb.cx') ? '查询' : ''}`,
            `${permissionStore.hasPermisson('wllb.xz') ? '新增' : ''}`,
            `${permissionStore.hasPermisson('wllb.sc') ? '删除' : ''}`,
            `${permissionStore.hasPermisson('wllb.sh') ? '审核' : ''}`,
            `${permissionStore.hasPermisson('wllb.dr') ? '导入' : ''}`,
            `${permissionStore.hasPermisson('wllb.mbxz') ? '模板下载' : ''}`,
          ]" @add="addHandler" @del="deleteHandler" @select="selectHandler" @audit="audits" @import="importHandler"
                   @excel="downloadHandler">
          </Toolbar>
          <Toolbar v-if="id == 2" :items="[
            `${permissionStore.hasPermisson('wllb.cx') ? '查询' : ''}`,
            `${permissionStore.hasPermisson('wllb.xz') ? '新增' : ''}`,
            `${permissionStore.hasPermisson('wllb.fs') ? '反审' : ''}`,
            `${permissionStore.hasPermisson('wllb.cx') ? '打印二维码' : ''}`,

          ]" @add="addHandler" @del="deleteHandler" @select="selectHandler" @counter="auditStates"
                   @printQRCode="printQRCode">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <!-- '导出', '导入' -->
        <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
        </Toolbar> -->
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
        <a-tab-pane title="未审核" key="1">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:97%;width: 100%;z-index:999 ;">
            <div style="width: 100%; height: 100%">
              <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
            </div>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane title="已审核" key="2">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:97%;width: 100%;z-index:999 ;">
            <div style="width: 100%; height: 100%">
              <encapsulation-agrid ref="table2Ref" :configaggrid="configTable2"></encapsulation-agrid>
            </div>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" height="100%"
              :mask-closable="false" popup-container=".main-base-style" placement="bottom" :visible="pageData.showAdd"
              unmountOnClose @ok="sideOk" @cancel="sideNo" :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="height: 100%; min-width:1500px; overflow:auto;">
        <a-form ref="formRef" layout="inline" :model="dataForm" :label-col-props="{ span: 13 }"
                :wrapper-col-props="{ span: 11 }" size="mini">

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料大类" field="bigClassName"
                       :rules="[{ required: true, message: '物料大类必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" class="bacClass" :disabled="pageData.isDetail || pageData.isDetailXG"
                      :loading="loadings" @click="bigClassClick" @change="focusSelsss" v-model="dataForm.bigClassName"
                      :filter-option="false" allow-search allow-clear>
              <a-option v-for="item in bigClassList">{{ item.bigClassName }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料中类" field="middleClassName"
                       :rules="[{ required: true, message: '物料中类必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" class="bacClass"
                      :disabled="pageData.isDetail || !dataForm.bigClassName || pageData.isDetailXG" :loading="loadings"
                      @click="middleClassClick" @change="focusSelsss2" v-model="dataForm.middleClassName"
                      :filter-option="false"
                      allow-search allow-clear>
              <a-option v-for="item in middleClassList">{{ item.middleClassName }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="物料小类" field="subClassName"
                       :rules="[{ required: true, message: '物料小类必填' }]" :validate-trigger="['change', 'blur']"
                       key="subClassName">
            <a-select popup-container="html" class="bacClass"
                      :disabled="pageData.isDetail || !dataForm.middleClassName || pageData.isDetailXG"
                      @change="focusSelsss3"
                      allow-clear allow-search v-model="dataForm.subClassName" :style="{ width: '320px' }"
                      @click="subClassClick">
              <a-option v-for="item in subClassList">{{ item.subClassName }}</a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料规格" field="specName"
                       :rules="[{ required: true, message: '物料规格必填' }]" :validate-trigger="['change', 'blur']"
                       key="specName">
            <a-select popup-container="html" class="bacClass" :disabled="pageData.isDetail" @focus="fouse"
                      @search="isDataIsfo" @change="changeName" v-model="dataForm.specName" :style="{ width: '320px' }"
                      allow-clear allow-search>
              <a-option v-for="item in dataListGg">{{ item.specName }}</a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="编号" field="materialCode"
                       :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                       :validate-trigger="['change', 'blur']">
            <a-input disabled class="bacClass" v-model="dataForm.materialCode" @blur="inputBlur"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料名称" field="materialName"
                       :rules="[{ required: true, message: '物料名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" :disabled="pageData.isDetail" v-model="dataForm.materialName"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="供应商名称">
            <a-select popup-container="html" class="bacClass" :disabled="pageData.isDetail" :loading="loadings1s1"
                      @search="handleSearchz" v-model="dataForm.providerName" :filter-option="false" allow-search
                      allow-clear
                      @focus="focusSelz">
              <a-option v-for="item in pageData.nameListz as any" :value="item.providerName">{{
                  item.providerName
                }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="单位" field="unit"
                       :rules="[{ required: true, message: '单位必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" class="bacClass" :disabled="pageData.isDetail || pageData.isDetailXG"
                      v-model="dataForm.unit" @search="searchUnit" @focus="focusunit" allow-clear allow-search
                      :filter-option="false" @change="unitChanges">
              <a-option v-for="item in pageData.unitList" :value="item['detailName']">{{
                  item["detailName"]
                }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="采购单位" field="purchaseUnit"
                       :rules="[{ required: true, message: '采购单位必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" class="bacClass" :disabled="pageData.isDetail || pageData.isDetailXG"
                      v-model="dataForm.purchaseUnit" @search="searchUnit1" @focus="focusunit1" allow-clear allow-search
                      :filter-option="false">
              <a-option v-for="item in pageData.unitList1" :value="item['detailName']">{{
                  item["detailName"]
                }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="换算比例" field="convertRate"
                       :rules="[{ required: true, message: '换算比例必填' }]" :validate-trigger="['change', 'blur']">
            <a-input-number v-model="dataForm.convertRate" :precision="0" class="input-demo bacClass"
                            :disabled="pageData.isDetail || pageData.isDetailXG" :min="1" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="采购单价" field="purchasePrice">
            <a-input-number v-model="dataForm.purchasePrice" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="2" :min="0"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="浓度单价" field="concentrationPrice">
            <a-input-number v-model="dataForm.concentrationPrice" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="2" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="销售单价" field="salePrice">
            <a-input-number v-model="dataForm.salePrice" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="2" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="安全库存" field="securityStockNum">
            <a-input-number class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.securityStockNum"
                            :precision="0" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="提前期" field="leadTime">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.leadTime"/>
          </a-form-item>


          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="贮存期限" field="storeTrem">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.storeTrem"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="品牌" field="brandName">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.brandName"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="经济批量" field="economicBatch">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.economicBatch"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="称料系统物料名称"
                       field="weighMaterialName">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.weighMaterialName"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="原料类型">
            <a-select popup-container="html" class="input-demo bacClass" :disabled="pageData.isDetail"
                      :loading="loading"
                      @search="handleSearchzs" v-model="dataForm.rawmaterialType" :filter-option="false" allow-search
                      allow-clear
                      @focus="focusSelzs">
              <a-option v-for="item in pageData.nameListzs" :value="item">{{
                  item
                }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="盈亏误差" field="profitLossError">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.profitLossError"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="生产商" field="producter">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.producter"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="化料温度" field="chemicalTemperature">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.chemicalTemperature"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="化料时间" field="chemicalTime">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.chemicalTime"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="浓度系数"
                       field="concentrationCoefficient">
            <a-input-number v-model="dataForm.concentrationCoefficient" :precision="2" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="包装数量" field="packageNum">
            <a-input-number v-model="dataForm.packageNum" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="0" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '420px' }" label-col-flex="120px" label="税率" field="texRate">
            <a-input-number v-model="dataForm.texRate" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="2" :min="0" :max="1000"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="中文名称" field="chinessName">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.chinessName"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="外文名称" field="englishName">
            <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.englishName"/>
          </a-form-item>

          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="最高库存" field="maxStockNum">
            <a-input-number v-model="dataForm.maxStockNum" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="0" :min="0" :max="1000"/>
          </a-form-item>
          <a-form-item :style="{ width: '420px' }" field="oldNewService">
            <el-checkbox v-model="dataForm.oldNewService" :true-label="1" :disabled="pageData.isDetail" :false-label="0"
                         style="font-size: 22px;font-weight: 600;color: #4E5969;" @change="isOne()">以旧换新
            </el-checkbox>
            <el-checkbox v-model="dataForm.fixAssetStatus" :true-label="1"
                         :disabled="pageData.isDetail || pageData.isDetailXG" :false-label="0"
                         style="font-size: 22px;font-weight: 600;color: #4E5969;" @change="isOne()">是否固定资产
            </el-checkbox>
            <el-checkbox v-model="dataForm.consumable" :true-label="1" :disabled="pageData.isDetail" :false-label="0"
                         style="font-size: 22px;font-weight: 600;color: #4E5969;">是否低质易耗品
            </el-checkbox>
          </a-form-item>
          <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="旧编号">
            <a-input class="input-demo bacClass" disabled v-model="objectMap"/>
          </a-form-item>

          <a-form-item style="width: 1022px;" label-col-flex="120px" label="备注" field="remark">
            <a-textarea class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.remark"
                        :max-length="400" allow-clear show-word-limit/>
          </a-form-item>
          <a-form-item field="picture" v-if="pageData.isShow">
            <a-upload list-type="picture-card" action="/" image-preview :limit="1" :customRequest="customUpload1"/>
          </a-form-item>
          <a-form-item field="picture" v-if="pageData.isShow1" @click="picClick">
            <a-image list-type="picture-card" :src="picUrl" @click="picClick"/>
          </a-form-item>
          <a-form-item field="picture" v-if="pageData.isShow2">
            <a-image list-type="picture-card" :src="picUrl"/>
          </a-form-item>
          <span v-if="pageData.isShow1" style="color: red;margin-top:80px;margin-left:230px;">*请点击修改图片</span>
        </a-form>
        <div style="font-size: 15px;">请选择成份：</div>
        <a-table stripe :bordered="true" :columns="tableColumnsCf" :loading="table.tableLoading" :data="pageData.cfList"
                 :rowKey="rowKey" size="mini">
          <template #del="{ record }">
            <icon-delete v-if="(record.partName != '') && pageData.isDetail == false"
                         style="font-size: 30px;cursor: pointer;color: red;" @click="delRow(record)"/>
          </template>
          <template #partName="{ record }">
            <div style="width:100%;">
              <a-select popup-container="html" class="input-demo bacClass" v-model="record.partName"
                        @change="changeCf(record)" @focus="focusSels1s" @search="handleSearchs1s" :loading="loading"
                        :filter-option="false" allow-search allow-clear :disabled="pageData.isDetail">
                <a-option v-for="item in pageData.nameLists1s">{{ item.partName }}</a-option>
              </a-select>
            </div>
          </template>
          <template #partRatio="{ record }">
            <div style="width:100%">
              <a-input-number v-model="record.partRatio" class="input-demo bacClass" :min="0" :max="100"
                              @change="changeBl(record)" :disabled="pageData.isDetail"/>
            </div>
          </template>
        </a-table>
      </div>
    </a-drawer>
    <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭" unmountOnClose>
      <template #title> 打印二维码</template>
      <div id="wllist" style="height: 500px;">
        <div v-for="(item, index) in qrDataList" :key="index" style="display: inline-block;margin-bottom: 10px;">
          <QrcodeVue :value="item['code']"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
            <span>物料编号: {{ decodeURI(item['materialCode']) }}</span>
            <br/>
            <span>物料名称: {{ decodeURI(item['materialName']) }}</span>
            <br/>
          </div>
        </div>

      </div>
    </a-modal>
  </pageTabelLayout>
</template>


<script setup lang="ts" name="ListMaterialsVue">
import {post} from '@/api/http'
import {usePagination, useRowKey, useRowSelection, useTable, useTableColumn} from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import {computed, onMounted, reactive, ref, watchEffect} from 'vue'
import {Message, Modal} from '@arco-design/web-vue';
import {FormInstance} from '@arco-design/web-vue/es/form';
import usePermission from '@/store/modules/permission';

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {baseURL} from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import {AnyColumn} from 'element-plus/es/components/table-v2/src/common';
import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import {log} from 'echarts/types/src/util/log';
import {simplifyMessages} from '@/api/messageSimplification'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import {saveOrUpdateGridState as saveOrUpdateGridState02} from '@/hooks/useGridState'

interface ProcurementType {
  "id": any
  "uid": any
  "materialCode": any
  "materialName": any
  "bigClassName": any
  "subClassName": any
  "specName": any
  "partName": any
  "providerName": any
  "maxStockNum": any
  "unit": any
  "packageNum": any
  "securityStockNum": any
  "salePrice": any
  "leadTime": any
  "storeTrem": any
  "brandName": any
  "economicBatch": any
  "weighMaterialName": any
  "purchasePrice": any
  "texRate": any
  "concentrationPrice": any
  "rawmaterialType": any
  "profitLossError": any
  "producter": any
  "chemicalTemperature": any
  "chemicalTime": any
  "concentrationCoefficient": any
  "remark": any
  "chinessName": any
  "englishName": any
  "validState": any
  "mustVerifyState": any
  "materialImg": any
  "deleteState": any
  "createName": any
  "createTime": any
  "updateName": any
  "updateTime": any
  "purchaseUnit": any
  "convertRate": any
  "partRatio": any
  subClassCode: any
  picture: string
  oldNewService: any
  fixAssetStatus: any
  consumable: any
}

const pageData = reactive<{
  nameList: [],
  nameLists: [],
  nameLists1: [],
  nameLists1s: any[],
  nameLists1s1: [],
  nameListz: [],
  nameListzs: [],
  showAdd: boolean,
  sideTitle: string,
  dropDownData: any,
  pageLoading: boolean,
  rHeight: any,
  btnList: any[],
  isEdit: boolean,
  cfList: any[],
  unitList: [],
  unitList1: [],
  dropDownData2: any,
  isDetail: boolean,
  file: string,
  isShow: boolean,
  isShow1: boolean,
  isShow2: boolean,
  materialCode: any,
  materialCode1: any,
  isDetailXG: Boolean
}>({
  isShow2: false,
  isShow1: false,
  isShow: false,
  file: '',
  nameList: [],
  nameLists: [],
  nameLists1: [],
  nameLists1s: [],
  nameLists1s1: [],
  nameListz: [],
  nameListzs: [],
  showAdd: false,
  sideTitle: '新增物料列表',
  dropDownData: "",
  pageLoading: false,
  rHeight: "",
  btnList: [],
  isEdit: false,
  cfList: [],
  unitList: [],
  unitList1: [],
  dropDownData2: "",
  isDetail: false,
  isDetailXG: false,
  materialCode: '',
  materialCode1: ''
});
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('wllb.xg')) {
  pageData.isEdit = true
}
if (permissionStore.hasPermisson('wllb.xq')) {
  pageData.isDetail = true
}
const table1Ref = ref<any>(null)
const table2Ref = ref<any>(null)
const tableColumns = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: "大类名称",
    field: "bigClassName",
    width: 150
  },
  {
    headerName: "中类名称",
    field: "middleClassName",
    width: 150
  },
  {
    headerName: "小类名称",
    field: "subClassName",
    width: 150
  },
  {
    headerName: "原编号",
    field: "initialMaterialCode",
    width: 150
  },
  {
    headerName: "编号",
    field: "materialCode",
    width: 150
  },
  {
    headerName: "物料名称",
    field: "materialName",
    width: 150
  },
  {
    headerName: "物料规格",
    field: "specName",
    width: 150
  },

  {
    headerName: "采购单位",
    field: "purchaseUnit",
    width: 150
  },
  {
    headerName: "单位",
    field: "unit",
    width: 150
  },
  {
    headerName: "换算比率",
    field: "convertRate",
    width: 150
  },
  {
    headerName: "以旧换新",
    field: "oldNewService",
    slotName: 'oldNewService',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" @change="a"></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.oldNewService == null ? false : props.params.data.oldNewService == 1 ? true : false
        const a = (data: any) => {
          post({
            url: '/purchase/MaterialInfo/updateOldNew',
            data: {
              id: props.params.data.id,
              oldNewService: data == true ? 1 : 0,
            }
          }).then((res: any) => {
            if (res.code === 200) {
              doRefresh()
            } else {
              Message.error(res.message)
            }
          })
        }
        return {
          val,
          a
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: "是否固定资产",
    field: "fixAssetStatus",
    slotName: 'fixAssetStatus',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" @change="a"></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.fixAssetStatus == null ? false : props.params.data.fixAssetStatus == 1 ? true : false
        const a = (data: any) => {
          post({
            url: '/purchase/MaterialInfo/updateOldNew',
            data: {
              id: props.params.data.id,
              fixAssetStatus: data == true ? 1 : 0,
            }
          }).then((res: any) => {
            if (res.code === 200) {
              doRefresh()
            } else {
              Message.error(res.message)
            }
          })
        }
        return {
          val,
          a
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: "是否低质易耗品",
    field: "consumable",
    slotName: 'consumable',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" @change="a"></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.consumable == null ? false : props.params.data.consumable == 1 ? true : false
        const a = (data: any) => {
          post({
            url: '/purchase/MaterialInfo/updateOldNew',
            data: {
              id: props.params.data.id,
              consumable: data == true ? 1 : 0,
            }
          }).then((res: any) => {
            if (res.code === 200) {
              doRefresh()
            } else {
              Message.error(res.message)
            }
          })
        }
        return {
          val,
          a
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: '图片',
    field: 'picture',
    slotName: 'picture',
    width: 150,
    cellRenderer: {
      template: `
        <a-image :src="p" style="margin: 0 auto; width: 100%; height: 100%;" fit="contain"/>
      `,
      setup(props: any) {
        let p = ref()
        p.value = baseURL + props.params.data.picture
        return {
          p,
        }
      }
    }
  },
  {
    headerName: "备注",
    field: "remark",
    width: 150
  },
  {
    headerName: "创建人",
    field: "createName",
    width: 150
  },
  {
    headerName: "创建时间",
    field: "createTime",
    width: 200
  },
  {
    headerName: "最后修改人",
    field: "updateName",
    width: 150
  },
  {
    headerName: "最后修改时间",
    field: "updateTime",
    width: 200
  },
  {
    headerName: '操作',
    field: 'action',
    slotName: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: {
      template: `
        <a-space>
          <a-tag class="tagCss" @click="a1" v-if="e">修改</a-tag>
          <a-tag class="tagCss" @click="a2" v-if="f">详情</a-tag>
        </a-space>
      `,
      setup(props: any) {
        const a1 = () => {
          editHandler(props.params.data)
        }
        const a2 = () => {
          detail(props.params.data)
        }
        return {
          a1,
          a2,
          e: pageData.isEdit,
          f: pageData.isDetail,
        }
      }
    }
  }
]
const tableColumns2 = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: "大类名称",
    field: "bigClassName",
    width: 150
  },
  {
    headerName: "中类名称",
    field: "middleClassName",
    width: 150
  },
  {
    headerName: "小类名称",
    field: "subClassName",
    width: 150
  },
  {
    headerName: "原编号",
    field: "initialMaterialCode",
    width: 150
  },
  {
    headerName: "编号",
    field: "materialCode",
    width: 150
  },
  {
    headerName: "物料名称",
    field: "materialName",
    width: 150
  },
  {
    headerName: "物料规格",
    field: "specName",
    width: 150
  },
  {
    headerName: "采购单位",
    field: "purchaseUnit",
    width: 150
  },
  {
    headerName: "单位",
    field: "unit",
    width: 150
  },
  {
    headerName: "换算比率",
    field: "convertRate",
    width: 150
  },
  {
    headerName: "以旧换新",
    field: "oldNewService",
    slotName: 'oldNewService',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" disabled></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.oldNewService == null ? false : props.params.data.oldNewService == 1 ? true : false
        return {
          val
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: "是否固定资产",
    field: "fixAssetStatus",
    slotName: 'fixAssetStatus',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" disabled></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.fixAssetStatus == null ? false : props.params.data.fixAssetStatus == 1
        return {
          val
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: "是否低质易耗品",
    field: "consumable",
    slotName: 'consumable',
    width: 150,
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" disabled></a-checkbox>
      `,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.consumable == null ? false : props.params.data.consumable == 1 ? true : false
        return {
          val
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '未选' : params.value == '1' ? '已选' : ''
      }
    }
  },
  {
    headerName: '图片',
    field: 'picture',
    slotName: 'picture',
    width: 150,
    cellRenderer: {
      template: `
        <a-image :src="p" style="margin: 0 auto; width: 100%; height: 100%;" fit="contain"/>
      `,
      setup(props: any) {
        let p = ref()
        p.value = baseURL + props.params.data.picture
        return {
          p,
        }
      }
    }
  },
  {
    headerName: "备注",
    field: "remark",
    width: 150
  },
  {
    headerName: "创建人",
    field: "createName",
    width: 150
  },
  {
    headerName: "创建时间",
    field: "createTime",
    width: 200
  },
  {
    headerName: "最后修改人",
    field: "updateName",
    width: 150
  },
  {
    headerName: "最后修改时间",
    field: "updateTime",
    width: 200
  },
  {
    headerName: '状态',
    field: 'obsoleteState',
    slotName: 'obsoleteState',
    pinned: 'right',
    width: 150,
    cellRenderer: {
      template: `
        <el-tag v-if="isDatas.obsoleteState == 0" type="success">生效</el-tag>
        <el-tag v-if="isDatas.obsoleteState == 1" type="danger">失效</el-tag>
      `,
      setup(props: any) {
        const isDatas = ref(props.params.data)
        return {
          isDatas
        }
      }
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '生效' : params.value == '1' ? '失效' : ''
      }
    }
  },
  {
    headerName: '操作',
    field: 'action',
    slotName: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: {
      template: `
        <a-space>
          <a-tag class="tagCss" @click="a2" v-if="f">详情</a-tag>
          <a-tag class="tagCss" @click="c">{{ b == 1 ? '生效' : '失效' }}</a-tag>
        </a-space>
      `,
      setup(props: any) {
        const c = () => {
          updateObsoleteState(props.params.data)
        }
        const a2 = () => {
          detail(props.params.data)
        }
        return {
          f: pageData.isDetail,
          a2,
          c,
          b: props.params.data.obsoleteState,
        }
      }
    }
  }
]
let configTable1 = {
  url: 'purchase/MaterialInfo/getPage', //接口路径
  queryData: {
    deleteState: 0,
    materialName: pageData.dropDownData,
    materialCode: pageData.materialCode,
    auditState: 0,
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns,
  fileName: 'ListMaterials01'
}
let configTable2 = {
  url: 'purchase/MaterialInfo/getPage', //接口路径
  queryData: {
    deleteState: 0,
    materialName: pageData.dropDownData2,
    materialCode: pageData.materialCode1,
    auditState: 1,
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns2,
  fileName: 'ListMaterials02'
}
// let fileList:any = []
const total = ref(0);
const page = ref(1);
const size = ref(10);
let id = ref(1);
const handoff = (key: any) => {
  id.value = key;
  if (id.value == 1) {
    doRefresh();
  } else {
    doRefresh2();
  }
}

function PageSize(val: any) {
  if (id.value == 1) {
    pagination.page = val
    doRefresh();
  } else {
    pagination.page = val
    doRefresh2();
  }

}

function change1(val: any) {
  if (id.value == 1) {
    pagination.pageSize = val
    doRefresh();
  } else {
    pagination.pageSize = val
    doRefresh2();
  }
}

//未审核 查询
function doRefresh() {
  table1Ref.value.setQuery({
    deleteState: 0,
    materialName: pageData.dropDownData,
    materialCode: pageData.materialCode,
    auditState: 0,
  })
}

//已审核 查询
function doRefresh2() {
  table2Ref.value.setQuery({
    deleteState: 0,
    materialName: pageData.dropDownData2,
    materialCode: pageData.materialCode1,
    auditState: 1,
  })
}

const {selectedRowKeys, onSelectionChange} = useRowSelection();
//成分表勾选返回的id

const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
const detail = (record: ProcurementType) => {
  pageData.isDetail = true
  pageData.cfList = [];
  let list = record.partName.split('/');
  for (let i = 0; i < list.length; i++) {
    var ob = {};
    ob['partName'] = list[i].split(',')[0]
    ob['partRatio'] = list[i].split(',')[1] == "" ? 0 : parseFloat(list[i].split(',')[1])
    pageData.cfList.push(ob)
  }

  for (let key in record) {
    dataForm[key] = record[key]
  }
  pageData.isShow2 = true
  pageData.isShow1 = false
  pageData.isShow = false
  picUrl.value = baseURL + record.picture
  pageData.sideTitle = '物料列表明细'
  pageData.showAdd = true
}
//成分信息表格
const tableColumnsCf = useTableColumn([
  {
    title: "操作",
    key: "del",
    dataIndex: "del",
    slotName: 'del',
    width: 150,
  },
  {
    title: "成分",
    key: "partName",
    dataIndex: "partName",
    slotName: 'partName',
    width: 150,
  },
  {
    title: "成分编号",
    key: "partCode",
    dataIndex: "partCode",
    width: 150,
  },
  {
    title: "比例",
    key: "partRatio",
    dataIndex: "partRatio",
    slotName: 'partRatio',
    width: 150,
  },

]);
let tc2: any[] = tableColumnsCf.map((o) => {

  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed']
  }
  obj['width'] = 250
  if (o.slotName === 'del') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['width'] = 80
    obj["lockPosition"] = "left"
    obj['cellRenderer'] = {
      template: `
        <icon-delete v-if="e" style="font-size: 30px;cursor: pointer;color: red;"
                     @click="delClick"/>`,
      setup(props: any) {
        const record = ref(props.params.data)
        const delClick = () => {
          delRow(props.params.data)
        }
        return {
          e: record.partName != '',
          delClick, record
        }
      }

    }
  }
  if (o.slotName === 'partName') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['width'] = 300
    // obj["lockPosition"] = "right"
    obj['cellRenderer'] = {
      template: `
        <a-select popup-container="html" class="bacClass" v-model="record.partName" @change="partChange"
                  @focus="focusSels1s" @search="handleSearchs1s" :loading="loading" :filter-option="false"
                  allow-search allow-clear>
          <a-option v-for="item in val">{{ item.partName }}</a-option>
        </a-select>`,
      setup(props: any) {
        const record = ref(props.params.data)
        let val = ref()
        val.value = pageData.nameLists1s
        const partChange = () => {
          changeCf(props.params.data)
        }
        //下拉框得到焦点
        const focusSels1s = () => {
          selCxAlls1s({deleteState: 0})
        }
        //下拉数据
        const optionss1s = ref<any>(pageData.nameLists1s);
        const loadings1s = ref(false);
        const handleSearchs1s = (value: any) => {
          if (value) {
            const ob = {partName: value}
            loadings1s.value = true;
            selCxAlls1s(ob);
            optionss1s.value = pageData.nameLists1s;
            loadings1s.value = false;
          } else {
            optionss1s.value = []
          }
        };

        //下拉框查询
        function selCxAlls1s(val: any) {
          post({
            url: "purchase/MaterialPart/getList",
            data: val
          }).then(({data, code}: any) => {
            if (code === 200) {
              pageData.nameLists1s = data;
            } else {
            }
          });
        }

        return {
          record,
          partChange,
          val,
          focusSels1s,
          handleSearchs1s,
          selCxAlls1s,
        }
      }

    }
  }
  if (o.slotName === 'partRatio') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['width'] = 300
    // obj["lockPosition"] = "right"
    obj['cellRenderer'] = {
      template: `
        <a-input-number v-model="record.partRatio" class="input-demo bacClass" :min="0" :max="100"
                        @change="ratioChange"/>`,
      setup(props: any) {
        const record = ref(props.params.data)
        const ratioChange = () => {
          changeBl(props.params.data)
        }
        return {
          record,
          ratioChange
        }
      }

    }
  }
  return obj
})


let a2 = [{
  showRowGroup: 'hide_def',
  "headerName": "",
  "checkboxSelection": true,
  "headerCheckboxSelection": true,
  "pinned": "left",
  "width": 50,
  resizable: false,
  filter: false,
  sortable: false,
  minWidth: 50,
  maxWidth: 50,
  lockPosition: "left",
}]
tc2 = a2.concat(tc2)
//下拉框得到焦点
const focusSel = () => {
  selCxAll({specName: ''})
}
//下拉数据
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
  if (value) {
    const ob = {specName: value}
    loading.value = true;
    window.setTimeout(() => {
      selCxAll(ob);
      options.value = pageData.nameList;
      loading.value = false;
    }, 200)
  } else {
    options.value = []
  }
};

//下拉框查询
function selCxAll(val: any) {
  post({
    url: "purchase/MaterialSpec/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameList = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

onMounted(() => {
  doRefresh();
  emitter.on("ListMaterials", () => {
    if (id.value == 1) {
      doRefresh();
    } else {
      doRefresh2();
    }
  });
  pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
  //表格的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight;
  }
  window.addEventListener('resize', () => {
    pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight
    //表格的高
    if (pageData.rHeight !== undefined) {
      pageData.rHeight = pageData.rHeight;
    }
  })
});
//查询
const selectHandler = () => {
  if (id.value == 1) {
    pagination.page = 1
    doRefresh();
  } else {
    pagination.page = 1
    doRefresh2();
  }
}
const addHandler = () => {
  pageData.cfList = [];
  pageData.isShow = true
  pageData.isDetailXG = false
  pageData.isDetail = false
  //清空数据
  for (const key in dataForm) {
    if (key == "id") {
      dataForm.id = null;
    } else if (key == "maxStockNum" ||
        key == "packageNum" ||
        key == "securityStockNum" ||
        key == "salePrice" ||
        key == "purchasePrice" ||
        key == "texRate" ||
        key == "concentrationPrice" ||
        key == "concentrationCoefficient") {
      dataForm[key] = 0;
    } else if (key == "convertRate") {
      dataForm[key] = 1;
    } else {
      dataForm[key] = '';
    }
  }
  focusSels1s()
  pageData.showAdd = true
  pageData.sideTitle = '新增物料列表'
  pageData.cfList.push({"partName": "", "partRatio": 0})

}

const dataForm: any = reactive({
  "id": "",
  "uid": "",
  "materialCode": "",
  "materialName": "",
  "specName": "",
  "partName": "",
  "providerName": "",
  "maxStockNum": 0,
  "unit": "",
  "packageNum": 0,
  "securityStockNum": 0,
  "salePrice": 0,
  "leadTime": "",
  "storeTrem": "",
  "brandName": "",
  "economicBatch": "",
  "weighMaterialName": "",
  "purchasePrice": 0,
  "texRate": 0,
  "concentrationPrice": 0,
  "rawmaterialType": "",
  "profitLossError": "",
  "producter": "",
  "chemicalTemperature": "",
  "chemicalTime": "",
  "concentrationCoefficient": 0,
  "remark": "",
  "chinessName": "",
  "englishName": "",
  "validState": "",
  "mustVerifyState": "",
  "materialImg": "",
  "deleteState": "",
  "createName": "",
  "createTime": "",
  "updateName": "",
  "updateTime": "",
  "purchaseUnit": '',
  "convertRate": 1,
  "partRatio": "",
  subClassCode: "",
  picture: '',
  oldNewService: 0,
  fixAssetStatus: 0,
  consumable: 0,
  MaterialInfoDetail: [],
  bigClassId: '',
  bigClassName: '',
  middleClassId: '',
  middleClassName: '',
  subClassId: '',
  subClassName: '',
})

// 表格准备事件
//未审核
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}
//已审核
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
  colState2.value = params.columnApi
}
const formRef = ref<FormInstance>()
const sideOk = () => {
  // console.log(fileList)
  formRef.value?.validate().then((err) => {
    if (!err) {
      //将成份拼接到后台
      dataForm.partName = '';
      let isCf = false
      if (pageData.cfList.length !== 0) {
        pageData.cfList.forEach(function (o: any) {
          if (o['partName'] != '' && o['partRatio'] != 0) {
            if (dataForm.partName == '') {
              dataForm.partName = o['partName'] + ',' + o['partRatio']
            } else {
              dataForm.partName += '/' + o['partName'] + ',' + o['partRatio']
            }
          }
        })
        console.log(pageData.cfList)
        if (!pageData.cfList[pageData.cfList.length - 1]['partName']) {
          pageData.cfList.pop()
        }
        dataForm.MaterialInfoDetail = pageData.cfList
        let poopInt = 0
        dataForm.MaterialInfoDetail.forEach((poop: any) => {
          poopInt += poop.partRatio
        })
        if (pageData.cfList.length != 0) {
          if (poopInt != 100) {
            Message.error('比例和必需100')
            return
          }
        }
      }

      if (pageData.sideTitle === "新增物料列表") {
        pageData.pageLoading = true
        dataForm.id = null
        dataForm.materialImg = null
        if (pageData.file != '') {
          let fd = new FormData()
          fd.append('file', pageData.file)
          axios.post(baseURL + '/minio/file/upload', fd, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
              .then((res: any) => {
                dataForm.picture = res['data']['data']['data']
                if (res.code == 500) {
                  Message.error(res.message)
                }
                post({
                  url: 'purchase/MaterialInfo/insert',
                  data: dataForm,
                })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '新增成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
              })
        } else {
          post({
            url: "purchase/MaterialInfo/insert",
            data: dataForm,
          }).then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields();
              pageData.showAdd = false;
              if (id.value == 1) {
                doRefresh();
              } else {
                doRefresh2();
              }
              Message.success({
                content: "新增成功",
                duration: 5000,
              });
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              });
            }
          }).finally(() => {
            pageData.pageLoading = false
          })
        }

      } else if (pageData.sideTitle === "修改物料列表") {
        dataForm.materialImg = null
        if (pageData.isShow = true) {
          let fd = new FormData()
          fd.append('file', pageData.file)
          axios.post(baseURL + '/minio/file/upload', fd, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
              .then((res: any) => {
                dataForm.picture = res['data']['data']['data']
                if (res.code == 500) {
                  Message.error(res.message)
                }
                post({
                  url: 'purchase/MaterialInfo/update',
                  data: dataForm,
                })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      //doRefresh();
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
              })
        } else {
          post({
            url: "purchase/MaterialInfo/update",
            data: dataForm,
          }).then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields();
              pageData.showAdd = false;
              if (id.value == 1) {
                doRefresh();
              } else {
                doRefresh2();
              }
              //清空数据
              for (const key in dataForm) {
                if (key == "id") {
                  dataForm.id = null;
                } else {
                  dataForm[key] = '';
                }
              }
              Message.success({
                content: "修改成功",
                duration: 5000,
              });
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              });
            }
          });
        }
      }
    }
  });
}

const sideNo = () => {
  pageData.showAdd = false
  pageData.isShow1 = false
  pageData.isShow2 = false
  pageData.isShow = false
  picUrl.value = ""
}
const deleteHandler = () => {
  if (table1Ref.value.getSelectedRows().length === 0 && table2Ref.value.getSelectedRows().length === 0) {
    Message.error('请先勾选');
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      if (id.value == 1) {
        post({
          url: 'purchase/MaterialInfo/delete',
          data: table1Ref.value.getSelectedRows().map((o: any) => {
            return o.id
          })
        }).then(({code, message}: any) => {
          if (code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000
            })
            page.value = 1
            doRefresh()
          } else {
            Message.error({
              content: message,
              duration: 5000
            })
          }
        })
      } else {
        post({
          url: 'purchase/MaterialInfo/delete',
          data: table2Ref.value.getSelectedRows().map((o: any) => {
            return o.id
          })
        }).then(({code, message}: any) => {
          if (code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000
            })
            page.value = 1
            doRefresh2()
          } else {
            Message.error({
              content: message,
              duration: 5000
            })
          }
        })
      }

    }
  })
}
let picUrl = ref()
const editHandler = (record: ProcurementType) => {
  pageData.isDetail = false
  // pageData.isDetailXG = true  
  pageData.isDetailXG = false  //zpf让改的
  pageData.cfList = [];
  objectMap.value = record.initialMaterialCode
  let list = record.partName.split('/');
  for (let i = 0; i < list.length; i++) {
    var ob = {};
    ob['partName'] = list[i].split(',')[0]
    ob['partRatio'] = list[i].split(',')[1] == "" ? 0 : parseFloat(list[i].split(',')[1])
    pageData.cfList.push(ob)
  }
  for (let key in record) {
    dataForm[key] = record[key]
  }
  dataForm.oldNewService = record.oldNewService == false ? 0 : 1
  dataForm.fixAssetStatus = record.fixAssetStatus == false ? 0 : 1
  dataForm.consumable = record.consumable == false ? 0 : 1
  if (record.picture != "") {
    pageData.isShow1 = true
    pageData.isShow = false
    pageData.isShow2 = false
    picUrl.value = baseURL + record.picture
  } else {
    pageData.isShow1 = false
    pageData.isShow2 = false
    pageData.isShow = true
  }
  // pageData.isShow = true
  dataForm.id = Number(record.id);
  pageData.sideTitle = '修改物料列表'
  post({
    url: 'purchase/MaterialInfoDetail/getList',
    data: {
      materialInfoId: record.id
    }
  }).then(({code, data}) => {
    if (code == 200) {
      pageData.cfList = data
      pageData.cfList.push({
        "partName": "", "partRatio": 0
      })
    }
  })
  pageData.showAdd = true
};
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
  return new Promise<void>(resolve => {
    if (window.encodeURI(value).indexOf('%') !== -1) {
      cb('填写的值不能包含中文！')
    }
    resolve()
  })

}
//input离开焦点 将小写转大写
const inputBlur = () => {
  dataForm.materialCode = dataForm.materialCode.toUpperCase();
}

//下拉框得到焦点
const focusSels = () => {
  selCxAlls({bigClassName: ''})
}
//下拉数据
const optionss = ref<any>(pageData.nameLists);
const loadings = ref(false);
const handleSearchs = (value: any) => {
  if (value) {
    const ob = {bigClassName: value}
    loadings.value = true;
    window.setTimeout(() => {
      selCxAlls(ob);
      optionss.value = pageData.nameLists;
      loadings.value = false;
    }, 200)
  } else {
    optionss.value = []
  }
};

//下拉框查询
function selCxAlls(val: any) {
  post({
    url: "purchase/MaterialBigClass/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      pageData.nameLists = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

//下拉框得到焦点
const focusSels1 = () => {
  selCxAlls1({bigClassName: dataForm.bigClassName, subClassName: ''})
}
//下拉数据
const optionss1 = ref<any>(pageData.nameLists1);
const loadings1 = ref(false);
const handleSearchs1 = (value: any) => {
  if (value) {
    const ob = {bigClassName: dataForm.bigClassName, subClassName: value}
    loadings1.value = true;
    window.setTimeout(() => {
      selCxAlls1(ob);
      optionss1.value = pageData.nameLists1;
      loadings1.value = false;
    }, 200)
  } else {
    optionss1.value = []
  }
};

//下拉框查询
function selCxAlls1(val: any) {
  if (dataForm.bigClassName == "") {
    Message.error('请先选择物料大类!')
    return
  }

  post({
    url: "purchase/MaterialSubClass/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      pageData.nameLists1 = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

//下拉框得到焦点
const focusSels1s = () => {
  selCxAlls1s({deleteState: 0})
}
const objectMap: any = ref('')
//下拉数据
const optionss1s = ref<any>(pageData.nameLists1s);
const loadings1s = ref(false);
const handleSearchs1s = (value: any) => {
  if (value) {
    const ob = {partName: value, deleteState: 0}
    loadings1s.value = true;

    selCxAlls1s(ob);
    optionss1s.value = pageData.nameLists1s;
    loadings1s.value = false;

  } else {
    optionss1s.value = []
  }
};

//下拉框查询
function selCxAlls1s(val: any) {
  post({
    url: "purchase/MaterialPart/getList",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameLists1s = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}


//下拉框得到焦点
const focusSels1s1 = () => {
  selCxAlls1s1({materialName: ''})
}
//下拉数据
const optionss1s1 = ref<any>(pageData.nameLists1s1);
const loadings1s1 = ref(false);
const handleSearchs1s1 = (value: any) => {
  if (value) {
    const ob = {materialName: value}
    loadings1s1.value = true;
    window.setTimeout(() => {
      selCxAlls1s1(ob);
      optionss1s1.value = pageData.nameLists1s1;
      loadings1s1.value = false;
    }, 200)
  } else {
    optionss1s1.value = []
  }
};

//下拉框查询
function selCxAlls1s1(val: any) {
  post({
    url: "purchase/MaterialInfo/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameLists1s1 = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

//下拉框得到焦点
const focusSelz = () => {
  selCxAllz({providerName: ''})
}
//下拉数据
const optionsz = ref<any>(pageData.nameListz);
const loadingz = ref(false);
const handleSearchz = (value: any) => {
  if (value) {
    const ob = {providerName: value}
    loadingz.value = true;
    window.setTimeout(() => {
      selCxAllz(ob);
      optionsz.value = pageData.nameListz;
      loadingz.value = false;
    }, 200)
  } else {
    optionsz.value = []
  }
};

//下拉框查询
function selCxAllz(val: any) {
  post({
    url: "purchase/Provider/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameListz = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

//下拉框得到焦点
const focusSelzs = () => {
  selCxAllzs({materialsCategoryName: '', deleteState: 0})
}
//下拉数据
const optionszs = ref<any>(pageData.nameListzs);
const loadingzs = ref(false);
const handleSearchzs = (value: any) => {
  if (value) {
    const ob = {materialsCategoryName: value, deleteState: 0}
    loadingzs.value = true;
    selCxAllzs(ob);
    optionszs.value = pageData.nameListzs;
    loadingzs.value = false;
  } else {
    options.value = []
  }
};

//下拉框查询
function selCxAllzs(val: any) {
  post({
    url: "product/RawmaterialType/getDrop",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameListzs = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

const headerShow = ref<boolean>(true)

let dataListXl = ref<any[]>([])
const code = () => {
  post({
    url: '/purchase/MaterialInfo/getMaxCode',
    data: {
      bigClassId: dataForm.bigClassId,
      middleClassId: dataForm.middleClassId,
      subClassId: dataForm.subClassId
    }
  }).then(({code, data}: any) => {
    if (code == 200) {
      dataForm.materialCode = data.maxApplyCode
    }
  })
}

let dataListGg = ref<any[]>([])

let dataListXls = ''
const isDatas = (val: any) => {
  post({
    url: 'purchase/MaterialSpec/getList',
    data: {
      subClassName: val,
    }
  }).then((res: any) => {
    if (res.code == 200) {
      // dataListGg = res.data
      code(val)
    } else {
      Message.error('获取物料规格失败')
    }
  })
  dataListXls = val
  dataForm.subClassCode = dataForm.subClassCode
  // code(val)
}
const changeName = (val: any) => {
}
let dataListCf = ref<any[]>([])
const fouse = () => {
  isDataIsfo({specName: ''})
}
const isDataIsfo = (ob: any) => {
  if (typeof ob == 'string') {
    ob = {"specName": ob}
  }
  post({
    url: 'purchase/MaterialSpec/getFieldValue',
    data: ob
  }).then((res: any) => {
    if (res.code == 200) {
      dataListGg.value = res.data
    } else {
      Message.error('获取物料成分失败')
    }
  })
}
//成份删除
const delRow = (record: any) => {
  if (pageData.cfList.length !== 1) {
    pageData.cfList = pageData.cfList.filter(function (o: any) {
      return o['partName'] !== record['partName']
    })
  } else {
    Message.warning('最后一条数据，不可删除！')
  }

}
//判断是否有重复
const changeCf = (record: any) => {
  pageData.nameLists1s.forEach((res: any) => {
    if (res.partName == record.partName) {
      record.partCode = res.partCode
    }
  })
  let count1 = 0;
  let count2 = 0;
  record.partRatio = 0;
  for (let index = 0; index < pageData.cfList.length; index++) {
    const element = pageData.cfList[index];
    if (element['partName'] == record['partName']) {
      count1++
    }
    if (element['partName'] == '') {
      count2++;
    }
    if (count1 > 1) {
      Message.warning('此成份已被选择过，请重新选择！')
      record['partName'] = ""
      record['partCode'] = ""
      return
    }
  }
  //选择完成份给用户再新增一行
  if (count2 == 0) {
    pageData.cfList.push({"partName": "", "partRatio": 0})
    // console.log(1111111111111);

  }
}
//判断比例列是否大于100
const changeBl = (record: any) => {
  setTimeout(function () {
    let num = 0;
    pageData.cfList.forEach(function (o: any) {
      if (o['partName'] != '' && o['partRatio'] != undefined && o['partRatio'] != null && o['partRatio'] != '') {
        console.log(parseFloat(o['partRatio']));
        num += parseFloat(o['partRatio']);
      }
    })
    if (num > 100) {
      Message.warning('此比率列已超过100,请重新填写！')
      record['partRatio'] = 0
    }
  }, 100);

}
const focusunit = () => {
  getUnitList("")
};
// 单位下拉框
const searchUnit = (value: any) => {
  if (value) {
    loading.value = true;
    getUnitList(value);
    options.value = pageData.unitList;
    loading.value = false;
  } else {
    options.value = []
  }
};
// 单位下拉框
const getUnitList = (val: any) => {
  post({
    url: 'dict/dictTypeDetail/getListByMap',
    data: {
      codeType: 17,
      detailName: val
    }
  }).then(({code, data}: any) => {
    if (code == 200) {
      pageData.unitList = data;
    } else {
      Message.error({
        content: '查询失败',
        duration: 5000
      })
    }
  });
};


const focusunit1 = () => {
  getUnitList1("")
};
// 单位下拉框
const searchUnit1 = (value: any) => {
  if (value) {
    loading.value = true;
    getUnitList1(value);
    options.value = pageData.unitList1;
    loading.value = false;
  } else {
    options.value = []
  }
};
// 单位下拉框
const getUnitList1 = (val: any) => {
  post({
    url: 'dict/dictTypeDetail/getListByMap',
    data: {
      codeType: 17,
      detailName: val
    }
  }).then(({code, data}: any) => {
    if (code == 200) {
      pageData.unitList1 = data;
    } else {
      Message.error({
        content: '查询失败',
        duration: 5000
      })
    }
  });
};
const handleChange = (_data: any) => {
  table.handleSuccess(_data);
};
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}
const defaultColDef2 = {
  sortable: true,
  resizable: true,
  filter: true,
}
//回车查询
const huiche = () => {
  selectHandler()
}
const huiche2 = () => {
  selectHandler()
}
//审核按钮
const audits = () => {
  if (table1Ref.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return;
  }
  let ids: any = []
  table1Ref.value.getSelectedRows().forEach((item: any) => {
    ids.push({
      id: item.id,
    })
  })
  Modal.confirm({
    title: '系统提示',
    content: '是否审核此单号',
    onOk() {
      post({
        url: "/purchase/MaterialInfo/audit",
        data: {
          id: ids,
          auditState: 1,
        },
      }).then((res: any) => {
        if (res.code === 200) {
          doRefresh();
          Message.success('审核通过')
        } else {
          Message.error(simplifyMessages(res.message))
        }
      })
    }
  })
}
//反审按钮
const auditStates = () => {
  if (table2Ref.value.getSelectedRows().length === 0) {
    Message.error('请勾选需要反审的数据')
    return
  }
  let ids: any = []
  table2Ref.value.getSelectedRows().forEach((item: any) => {
    ids.push({
      id: item.id,
    })
  })
  Modal.confirm({
    title: '系统提示',
    content: '是否反审此订单',
    onOk() {
      post({
        url: '/purchase/MaterialInfo/audit',
        data: {
          id: ids,
          auditState: 0,
        },
      }).then((res: any) => {
        if (res.code === 200) {
          doRefresh2()
          //   emitter.emit('shauxings')
          Message.success('反审成功')
        } else {
          Message.error(simplifyMessages(res.message))
        }
      })
    },
  })
}
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
//模板下载
const downloadHandler = () => {
  axios.get(baseURL + '/purchase/MaterialInfo/uploadModel', {
    responseType: 'blob',
    headers: {
      token: sessionStorage.getItem('USER-TOKEN-KEY')
    }
  }).then((res) => {
    if (res.status === 200) {
      filedownload(res.data, '物料列表.xlsx')
    }
  })
}
//导入
const importHandler = () => {

  const inputEle: HTMLInputElement = document.createElement('input')
  inputEle.type = 'file'
  inputEle.id = 'fileUploadExcel'
  inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
  inputEle.addEventListener('change', (e) => {
    const formData = new FormData()
    if (inputEle.files !== null) {
      formData.append('file', inputEle.files[0] || '')
    } else {
      Message.warning('未选择文件！');
      return
    }
    pageData.pageLoading = true
    axios.post(baseURL + '/purchase/MaterialInfo/importModelData', formData, {
      headers: {
        "Content-Type": 'multipart/form-data',
        "token": sessionStorage.getItem('USER-TOKEN-KEY')
      },
    }).then((result) => {
      if (result.data['code'] === 200) {
        Message.success('导入成功')
      } else {
        Message.error(result.data.message)
      }

    }).finally(() => {
      pageData.pageLoading = false
      doRefresh2()
    })
  })
  inputEle.click()
}
const unitChanges = (e: any) => {
  if (dataForm.purchaseUnit == '') {
    dataForm.purchaseUnit = e
  }
}

//生效不生效
function updateObsoleteState(record: any) {
  Modal.confirm({
    title: '系统提示',
    content: '是否继续订单进行操作',
    onOk() {
      let state = null
      if (record.obsoleteState == 1) {
        state = 1
      } else {
        state = 0
      }
      post({
        url: '/purchase/MaterialInfo/updateObsoleteState',
        data: {
          id: record.id,
          obsoleteState: state
        }
      }).then((res: any) => {
        if (res.code === 200) {
          doRefresh2()
          Message.success('成功！')
        } else {
          Message.error(res.message)
        }
      })
    }
  })

}

let qrDataList = ref([])
const visible = ref(false)

const handleOk = () => {
  printJS({
    printable: 'wllist',
    type: 'html',
    targetStyles: ['*'],
  })
  visible.value = false
}
const handleCancel = () => {
  visible.value = false
}
//打印二维码
const printQRCode = () => {
  if (table2Ref.value.getSelectedRows().length === 0) {
    Message.error('请勾选需要打印的数据')
    return
  }
  visible.value = true
  let row = table2Ref.value.getSelectedRows()
  row.forEach(function (o: any) {
    let ob = {}
    ob['materialCode'] = o['materialCode']
    ob['materialName'] = o['materialName']
    ob['code'] = JSON.stringify({
      materialCode: encodeURI(o.materialCode)

    })
    qrDataList.value.push(ob)
  })
}

//文件上传
function customUpload1(info: any) {
  info.onSuccess('')
  pageData.file = info.fileItem.file
  return info
}

const picClick = () => {
  pageData.isShow = true
  pageData.isShow1 = false
  pageData.isShow2 = false
}

const isOne = () => {
  if (dataForm.fixAssetStatus == true && dataForm.oldNewService == true) {
    Message.warning('以旧换新和固定资产只能选其一!')
    dataForm.fixAssetStatus = false
    dataForm.oldNewService = false
  }
}

const bigClassList: any = ref([])

const bigClassClick = () => {
  post({
    url: 'purchase/MaterialBigClass/getList',
    data: {}
  }).then(({data}) => {
    bigClassList.value = data
  })
}
const focusSelsss = (val: any) => {
  bigClassList.value.forEach((res: any) => {
    if (res.bigClassName == val) {
      dataForm.bigClassId = res.id
    }
  })
  dataForm.subClassName = ''
  dataForm.materialCode = ''
  dataForm.middleClassName = ''
}

const middleClassList: any = ref([])
const middleClassClick = () => {
  post({
    url: 'purchase/MaterialMiddleClass/getList',
    data: {
      bigClassId: dataForm.bigClassId
    }
  }).then(({data}) => {
    middleClassList.value = data
  })
}
const focusSelsss2 = (val: any) => {
  middleClassList.value.forEach((res: any) => {
    if (res.middleClassName == val) {
      dataForm.middleClassId = res.id
    }
  })
  dataForm.subClassName = ''
}

const subClassList: any = ref([])
const subClassClick = () => {
  post({
    url: 'purchase/MaterialSubClass/getList',
    data: {
      middleClassId: dataForm.middleClassId
    }
  }).then(({data}) => {
    subClassList.value = data
  })
}
const focusSelsss3 = (val: any) => {
  subClassList.value.forEach((res: any) => {
    if (res.subClassName == val) {
      dataForm.subClassId = res.id
      dataForm.subClassCode = res.subClassCode
    }
  })

  // code(dataForm.subClassCode)
  code()
  dataListXls = val
}
const concatMaterialName = computed(() => {
  return `${dataForm.brandName}${dataForm.subClassName}${dataForm.specName}`
})
// watchEffect(() => {
//   dataForm.materialName = concatMaterialName.value
// })
</script>

<style lang="less" scoped>
.arco-image-img {
  width: 80px;
  height: 80px;
  margin-left: 600px;
  margin: 0 auto;
}

div.arco-image-error {
  width: 80px;
  height: 80px;
  margin-left: 600px;
  margin: 0 auto;
}

:deep(.ag-cell-wrapper) {
  height: 100% !important;
}

:deep(.ag-cell-value) {
  height: 100% !important;
}

:deep(.arco-image-img ) {
  height: 100%;
}
</style>